package drds.server.net.packet;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import drds.server.net.SessionContext$LifeCycle;

/**
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class BinaryPacket extends Packet {
	public static final byte OK = 1;
	public static final byte ERROR = 2;
	public static final byte HEADER = 3;
	public static final byte FIELD = 4;
	public static final byte FIELD_EOF = 5;
	public static final byte ROW = 6;
	public static final byte PACKET_EOF = 7;

	public byte[] bytes;

	public void read(InputStream inputStream) throws IOException {
		this.packetLength = StreamUtil.readInt3(inputStream);
		this.packetId = StreamUtil.read(inputStream);
		byte[] bytes = new byte[this.packetLength];
		StreamUtil.read(inputStream, bytes, 0, bytes.length);
		this.bytes = bytes;
	}

	@Override
	public ByteBuffer write(ByteBuffer byteBuffer, SessionContext$LifeCycle sessionContext, boolean writeSocketIfFull) {
		byteBuffer = sessionContext.checkWriteByteBuffer(byteBuffer, sessionContext.getPacketHeaderSize(), writeSocketIfFull);
		ByteBufferUtil.writeInt3(byteBuffer, computePacketSize());
		byteBuffer.put(packetId);
		byteBuffer = sessionContext.writeToByteBuffer(bytes, byteBuffer);
		return byteBuffer;
	}

	@Override
	public int computePacketSize() {
		return bytes == null ? 0 : bytes.length;
	}

}